package com.balabala.gym_goods.service.impl;

import com.balabala.api.VenuesFeignClient;
import com.balabala.dto.VenuesDto;
import com.balabala.gym_enum.ResultEnum;
import com.balabala.gym_goods.mapper.CourseMapper;
import com.balabala.gym_goods.pojo.dto.*;
import com.balabala.gym_goods.pojo.entity.CoachSchedule;
import com.balabala.gym_goods.pojo.entity.Course;
import com.balabala.gym_goods.pojo.entity.CourseCardVenues;
import com.balabala.gym_goods.pojo.vo.CourseVo;

import com.balabala.gym_goods.pojo.vo.*;
import com.balabala.gym_goods.service.CoachScheduleService;
import com.balabala.gym_goods.service.CourseCardVenuesService;
import com.balabala.gym_goods.service.CourseService;
import com.balabala.gym_system.api.AdminFeignClient;

import com.balabala.gym_goods.service.UserCourseService;
import com.balabala.gym_system.api.AddReservationInfoFeignClient;
import com.balabala.gym_system.api.AdminFeignClient;
import com.balabala.gym_system.api.CoachFeignClient;
import com.balabala.gym_system.pojo.dto.ReservationInfoDto;

import com.balabala.gym_system.pojo.vo.CoachVo;
import com.balabala.result.Result;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;

/**
 * @author fsj
 * @date 2023/5/5 18:20
 */
@Service
@Slf4j
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements CourseService {
    @Autowired
    private CoachFeignClient coachFeignClient;
    @Autowired
    private AdminFeignClient adminFeignClient;
    @Autowired
    private VenuesFeignClient venuesFeignClient;
    @Autowired
    private CourseService courseService;
    @Autowired
    private CoachScheduleService coachScheduleService;
    @Autowired
    private UserCourseService userCourseService;
    @Autowired
    private AddReservationInfoFeignClient addReservationInfoFeignClient;

    @Autowired
    private CourseCardVenuesService courseCardVenuesService;


    @Override
    public int addCourse(CourseDto courseDto) {
        Course course = new Course();
        BeanUtils.copyProperties(courseDto, course);
        return getBaseMapper().insert(course);
    }


    @Override
    public List<CourseVo> findCourseByName(CourseByNameQueryDto courseByNameQueryDto) {
        return getBaseMapper().findCourseByName(courseByNameQueryDto);
    }

    /**
     * 当天的团课
     *
     * @return
     */
   /* @Override
    public List<BookCourseAppVo> findByTime() {
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String format = simpleDateFormat.format(date);


        List<BookCourseAppVo> byTimeByVenues = getBaseMapper().findByNewTimeByVenues(findCoachByTimeDto);

        return byTimeByVenues;
    }*/

    /**
     * 根据时间查询
     *
     * @param
     * @return
     */
    @Override
    public List<BookCourseAppVo> findByDate(FindCoachByTimeDto findCoachByTimeDto) {

        List<BookCourseAppVo> byTimeByVenues = getBaseMapper().findByTimeByVenues(findCoachByTimeDto);
        log.info("查询出来的标签{}", byTimeByVenues.get(0).getLabel());
        List<BookCourseAppVo> list = new ArrayList<>();
        byTimeByVenues.forEach(b -> {
            Result<CoachVo> coachById = coachFeignClient.getCoachById(b.getCoachId());
            BookCourseAppVo bookCourseAppVo = new BookCourseAppVo();

            BeanUtils.copyProperties(b, bookCourseAppVo);
            //拼接时间
            //设置Vo的上课的时间区间 9:00-10:00
            String str = DateFormatUtils.format(b.getStartTime(), "yyyy-MM-dd HH:mm:SS");

            String[] s01 = str.split(" ");
            String s1 = s01[1];
            String[] split1 = s1.split(":");
            String s2 = split1[0] + ":" + split1[1];


            String end = DateFormatUtils.format(b.getEndTime(), "yyyy-MM-dd HH:mm:SS");

            String[] s02 = end.split(" ");
            String s3 = s02[1];
            String[] split2 = s3.split(":");
            String s22 = split2[0] + ":" + split2[1];

            bookCourseAppVo.setTimeRange(s2 + "~" + s22);

            //venuesFeignClient
            Result<VenuesDto> venuesById = venuesFeignClient.getVenuesById(b.getVenuesId());

            //设置场馆名称
            bookCourseAppVo.setVenuename(venuesById.getData().getName());
            bookCourseAppVo.setCoachName(coachById.getData().getName());
            list.add(bookCourseAppVo);
        });

        return list;

    }

    /**
     * 根据课程id查询课程信息和教练信息
     *
     * @param id
     * @return
     */
    @Override
    public CourseVo findCourseById(Long id) {
        CourseVo courseVo = new CourseVo();
        Course course = getBaseMapper().selectById(id);
        BeanUtils.copyProperties(course, courseVo);
        Result<CoachVo> coachById = coachFeignClient.getCoachById(course.getCoachId());
        courseVo.setCoachVo(coachById.getData());
        return courseVo;
    }

    /**
     * 团课添加预约信息
     *
     * @param addNumDto
     * @return
     */
    @Override
    @Transactional
    public Result addNum(AddNumDto addNumDto) {
        Course course = getBaseMapper().selectById(addNumDto.getCourseId());
        //判断是否达人数上限
        if (course.getNumAppointment() + addNumDto.getNum() > course.getMastClassNum()) {
            return Result.fail(ResultEnum.MORE_NUMBER);
        }
        course.setNumAppointment(course.getNumAppointment() + addNumDto.getNum());
        //重新储存
        int insert = getBaseMapper().updateById(course);
        //调用远程接口存取预约信息

        ReservationInfoDto reservationInfoDto = new ReservationInfoDto();
        reservationInfoDto.setCourseId(addNumDto.getCourseId());
        reservationInfoDto.setBookingNum(addNumDto.getNum());
        reservationInfoDto.setRemark(reservationInfoDto.getRemark());
        reservationInfoDto.setUserId(addNumDto.getUserId());
        Result result = addReservationInfoFeignClient.addReservationInfo(reservationInfoDto);
        if (insert > 0 && result.getCode() == 0) {
            return Result.ok();
        }

        return Result.fail();
    }


    /**
     * 团课课表的列表
     *
     * @return
     */
    public List<CourseListVo> getListAll() {

        //课程表列表查询
        List<CourseQueryVo> courseList = getBaseMapper().getListAll();

        //新建CourseListVo的list
        List<CourseListVo> courseListVoList = new ArrayList<>();

        courseList.forEach(course -> {
            log.info("传递的参数为:{},", course.getCoachId());

            //远程调用教练信息
            Result<CoachVo> coachById = coachFeignClient.getCoachById(course.getCoachId());
            CourseListVo courseListVo = new CourseListVo();
            BeanUtils.copyProperties(course, courseListVo);

            courseListVo.setOrderNumber(String.valueOf(course.getNumAppointment() + "/" + course.getClassOrderNumber()));
            //设置Vo的上课的时间区间 9:00-10:00
            String str = DateFormatUtils.format(course.getStartTime(), "yyyy-MM-dd HH:mm:SS");
            String[] split = str.split(":");
            String str1 = split[0] + ":" + split[1];
            String end = DateFormatUtils.format(course.getEndTime(), "yyyy-MM-dd HH:mm:SS");
            String[] time = end.split(" ");
            String time1 = time[1];
            String[] time2 = time1.split(":");
            String time3 = time2[0] + ":" + time2[1];
            String time4 = str1 + "至" + time3;

            courseListVo.setCourseTime(time4);
            System.out.println(time4);

            //拷贝
            BeanUtils.copyProperties(coachById, courseListVo);
            if (coachById.getData().getName() != null) {
                log.info("coach远程调用的数据为:{}", coachById.getData().getName());
                courseListVo.setCoachName(coachById.getData().getName());
            }

            //远程调用场馆信息
            Result<VenuesDto> venuesById = venuesFeignClient.getVenuesById(course.getVenuesId());
            BeanUtils.copyProperties(venuesById, courseListVo);
            if (venuesById.getData().getName() != null) {
                log.info("venues远程调用的数据为:{}", venuesById.getData().getName());
                courseListVo.setVenuesName(venuesById.getData().getName());
            }
            if (venuesById.getData().getAddress() != null) {
                log.info("venues远程调用的数据为:{}", venuesById.getData().getAddress());
                courseListVo.setVenuesAddress(venuesById.getData().getAddress());
            }


            courseListVoList.add(courseListVo);
        });
        return courseListVoList;
    }

    /**
     * 团课课程的列表
     *
     * @return
     */
    public List<CourseFindResultVo> getAll() {

        //团课课程的查询
        List<CourseFindVo> courseList = getBaseMapper().getAll();

        //新建CourseListVo的list
        List<CourseFindResultVo> courseListVoList = new ArrayList<>();
        for (CourseFindVo co : courseList) {

            if (co.getCoachId() == 0 || co.getCoachId() == null) {
                continue;
            }
            log.info("传递的参数为:{},", co.getCoachId());

            //远程调用教练信息
            Result<CoachVo> coachById = coachFeignClient.getCoachById(co.getCoachId());
            CourseFindResultVo courseListVo = new CourseFindResultVo();
            BeanUtils.copyProperties(co, courseListVo);
            //拷贝
            BeanUtils.copyProperties(coachById, courseListVo);


            if (coachById.getData().getName() == null) {
                courseListVo.setCoachName(null);
            } else {
                courseListVo.setCoachName(coachById.getData().getName());
            }


            if (coachById.getData() == null) {

                courseListVo.setCoachName(null);
            } else {
                log.info("coach远程调用的数据为:{}", coachById.getData().getName());
                courseListVo.setCoachName(coachById.getData().getName());
            }


            courseListVoList.add(courseListVo);
        }
        return courseListVoList;
    }

    /**
     * 私教添加用户预约信息
     *
     * @param addAppointmentDto
     */
    @Override
    @Transactional
    public Result addAppointment(AddAppointmentDto addAppointmentDto) {
        //先查询出当前课程的预约人数判断是否超过预约人数
        Course course = getBaseMapper().selectById(addAppointmentDto.getCourseId());
        if (course.getNumAppointment() + addAppointmentDto.getNumPeople() > course.getMastClassNum()) {
            return Result.fail(ResultEnum.MORE_NUMBER);
        }
        Boolean aBoolean = getBaseMapper().addNum(addAppointmentDto.getCourseId(), addAppointmentDto.getNumPeople());
        //调用远程fegin接口
        ReservationInfoDto reservationInfoDto = new ReservationInfoDto();

        reservationInfoDto.setCourseId(addAppointmentDto.getCourseId());
        reservationInfoDto.setUserId(addAppointmentDto.getUserId());
        reservationInfoDto.setRemark(addAppointmentDto.getRemark());
        reservationInfoDto.setBookingNum(addAppointmentDto.getNumPeople());
        //调远程feign接口添加预约信息
        Result result = addReservationInfoFeignClient.addReservationInfo(reservationInfoDto);
        return Result.ok();
    }

    @Override
    public Boolean updateList(CourseDto courseDto) {
//        Coach coach = new Coach();
//
//        //修改教练对应的场馆
//        this.updateVenue(coachDto);
//
//        BeanUtils.copyProperties(coachDto, coach);
//        int i = getBaseMapper().updateById(coach);
//        if (i > 0) {
//            return true;
//        }
//        return false;
        return true;
    }

    @Override
    public Boolean addPrivateCourseSchedule(AddCoachScheduleDto addCoachScheduleDto) {
        CoachSchedule coachSchedule = new CoachSchedule();
        BeanUtils.copyProperties(addCoachScheduleDto, coachSchedule);
        coachScheduleService.save(coachSchedule);
        courseCardVenuesService.save(addCoachScheduleDto.getCourseCardVenues());

        return true;
    }

    @Override
    public List<CourseFindResultVo> findById(Long id) {
        //团课课程的查询
        List<CourseFindVo> byId = getBaseMapper().findById(id);

        //新建CourseListVo的list
        List<CourseFindResultVo> courseListVoList = new ArrayList<>();
        for (CourseFindVo co : byId) {

            log.info("传递的参数为:{},", co.getCoachId());
            //远程调用教练信息
            Result<CoachVo> coachById = coachFeignClient.getCoachById(co.getCoachId());
            CourseFindResultVo courseListVo = new CourseFindResultVo();
            BeanUtils.copyProperties(co, courseListVo);
            //拷贝
            BeanUtils.copyProperties(coachById, courseListVo);
            courseListVo.setCoachName(coachById.getData().getName());


            log.info("coach远程调用的数据为:{}", coachById.getData().getName());

            courseListVoList.add(courseListVo);
        }
        return courseListVoList;

    }

    /**
     * 根据教练id查找课程信息
     *
     * @param id
     * @return
     */
    @Override
    public List<Course> findByCoachId(Long id) {
        return getBaseMapper().findByCoachId(id);
    }

    /**
     * 删除课表信息
     *
     * @param id
     * @return
     */
    @Override
    public Boolean deleteByCourseScheduleId(Long id) {
        return coachScheduleService.removeById(id);
    }

    /**
     * 添加课表信息
     *
     * @param addCourseScheduleDto
     * @return
     */
    @Override
    public Boolean addCourseSchedule(AddCourseScheduleDto addCourseScheduleDto) {
        String workTime = addCourseScheduleDto.getWorkTime();
        String str = workTime;
        String[] s = str.split("至");
        log.info("开始时间{}", s[0]);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:MM");
        Date startTime = null;
        Date endTime = null;
        try {
            startTime = simpleDateFormat.parse(s[0]);
            String[] str2 = str.split(" ");
            String s2 = str2[0] + " " + s[1];
            endTime = simpleDateFormat.parse(s2);

        } catch (ParseException e) {
            e.printStackTrace();
            log.info("转化失败:{}", endTime);

        }
        CoachSchedule coachSchedule = new CoachSchedule();
        BeanUtils.copyProperties(addCourseScheduleDto, coachSchedule);
        coachSchedule.setStartTime(startTime);
        coachSchedule.setEndTime(endTime);
        return coachScheduleService.save(coachSchedule);
    }

    @Override
    @Transactional
    public CoachScheduleVo findAllCoachSch(Long id) {
        List<CoachSchedule> byVenusId = getBaseMapper().findByVenusId(id);
        List<CourseQueryByCoachVo> courses = new ArrayList<>();
        byVenusId.forEach(coachSchedule -> {
            if (coachSchedule.getCourseId() != null) {
                CourseQueryByCoachVo courseQueryByCoachVo = new CourseQueryByCoachVo();
                Course byId = courseService.getById(coachSchedule.getCourseId());
                 BeanUtils.copyProperties(byId,courseQueryByCoachVo);
                Result<CoachVo> coachById = coachFeignClient.getCoachById(byId.getCoachId());
                courseQueryByCoachVo.setCoachName(coachById.getData().getName());
                courses.add(courseQueryByCoachVo);

            }
        });

        Result<VenuesDto> venuesById = venuesFeignClient.getVenuesById(id);
        CoachScheduleVo coachScheduleVo = new CoachScheduleVo();
        coachScheduleVo.setVenusName(venuesById.getData().getName());
        coachScheduleVo.setCoachId(venuesById.getData().getId());
        coachScheduleVo.setCourse(courses);
        return coachScheduleVo;

    }

}
